#define SERVER_PORT "36600"
#define MAX_PENDING_CONNECTIONS SOMAXCONN

#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>


int main()
{

	int listen_socket, work_socket, recv_len;
	int mail_socket, remote_addr_len;
	struct addrinfo hints, *res;
	struct sockaddr_storage remote_addr;
	char recvBuf[1024];
	int i,size;
	char path[1024];
	FILE* psegment;
	int open_ret, bytes_written;

	memset(recvBuf, 0, sizeof(recvBuf));
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	getaddrinfo(NULL,SERVER_PORT,&hints,&res);

	/* Initiate the listening socket */
	if ((listen_socket = socket(res->ai_family,
							   res->ai_socktype,
							   res->ai_protocol)) == -1)
	{
		   printf("Failed to create a listening socket.\n\n");
		   return 1;
	}

	/* Bind us to port SERVER_PORT */
	if (bind(listen_socket,
				   res->ai_addr,
				   res->ai_addrlen) == -1)
	{
		   printf("Failed bind to %s.errno = %d\r\n",SERVER_PORT, errno);
		   close(listen_socket);
		   return 1;
	}

	/* Set up listening */
	if (listen(listen_socket,
			  MAX_PENDING_CONNECTIONS) == -1)
	{
		   printf("Failed to set up listening.\n\n");
		   close(listen_socket);
		   return 1;
	}

	printf("after listen\n");
	remote_addr_len = sizeof(remote_addr);
	while ((work_socket = accept(listen_socket,
								(struct sockaddr*)&remote_addr,
								&remote_addr_len)) != -1)
	{
		  printf("after accept\n");
		   size = 0;
		   /* First recv a client key for storage. */
		   read(work_socket, path, 1024, 0);
			
		   printf("path = %s\n", path);	   
		   /* Save log to a local file. */
	
		   open_ret = open(path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
		   if ( -1 == open_ret )
		   {
			printf("open err : %d\n", errno);
			continue;
		   }
		   //printf("open_ret = %d, recvBuf =%s\n", open_ret, recvBuf);
		   while ((recv_len = read(work_socket, recvBuf, 1024, 0)) > 0)
		   {
			printf("recv_len = %d, recvBuf=%s\n", recv_len, recvBuf);
			/*
			for ( i = 0; i < recv_len; i++)
			{
				printf("data=%x,i=%d", recvBuf[i],i);
			}
			printf("\n");		
			*/
			bytes_written =  write( open_ret, recvBuf, recv_len);
			printf("bytes_written=%d\n", bytes_written);
			size += bytes_written;
		   }
		   printf("received data: %6d bytes\n", size);
		   close(work_socket);
		   printf("close work_socket\n");
	}

	close(listen_socket);
	return 0;
}
